package com.es.piomessages.model;

import com.es.piomessages.MainActivity;
import com.es.piomessages.R;
import com.es.piomessages.SettingsActivity;
import com.sun.org.apache.bcel.internal.generic.GETSTATIC;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;

public class AlarmeEntrega extends BroadcastReceiver{
	GestorDeMenssagens gestor;
	private static int notifyId = 0;

	@Override
	public void onReceive(Context context, Intent intent) {

		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
		boolean notify = sharedPref.getBoolean(SettingsActivity.KEY_PREF_NOTIFY, true);
		System.out.println("notifica? "+ notify);
		boolean isThereMsg = false;
		Menssagem msg;

		try {
			gestor = GestorDeMenssagens.getInstance();
			isThereMsg = gestor.isThereNewMessage();
			msg = gestor.getMessage();
			
			if(notify && isThereMsg){
				notificaUsuario(context, msg);
			}
			
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
	}

	private void notificaUsuario(Context context, Menssagem msg){
		NotificationCompat.Builder mBuilder =
				new NotificationCompat.Builder(context)
		.setSmallIcon(R.drawable.scroll)
		.setContentText(msg.getMsg())
		.setContentTitle(context.getString(R.string.notifycation_title))
		.setAutoCancel(true);
		// Creates an explicit intent for an Activity in your app
		Intent resultIntent = new Intent(context, MainActivity.class);

		// The stack builder object will contain an artificial back stack for the
		// started Activity.
		// This ensures that navigating backward from the Activity leads out of
		// your application to the Home screen.
		TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
		// Adds the back stack for the Intent (but not the Intent itself)
		stackBuilder.addParentStack(MainActivity.class);
		// Adds the Intent that starts the Activity to the top of the stack
		stackBuilder.addNextIntent(resultIntent);
		PendingIntent resultPendingIntent =
				stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
		mBuilder.setContentIntent(resultPendingIntent);
		NotificationManager mNotificationManager =
				(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		// mId allows you to update the notification later on.
		mNotificationManager.notify(notifyId, mBuilder.build());


	}

}